﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command.AppaLL;
using MediatR;
using System.Transactions;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler.AppHandler
{
    public class AddAppCommandHandler : IRequestHandler<AddAppCommand, ApiResult<int>>
    {
        IBaseReponsitory<App> Apps;
        IBaseReponsitory<RoleApp> RoleApps;

        public AddAppCommandHandler(IBaseReponsitory<App> Apps, IBaseReponsitory<RoleApp> RoleApps)
        {
            this.Apps = Apps;
            this.RoleApps = RoleApps;
        }

        public async Task<ApiResult<int>> Handle(AddAppCommand request, CancellationToken cancellationToken)
        {
            var list = Apps.GetQuery().Where(x => x.App_Name == request.Apps.App_Name && !x.App_IsDel).ToList();
            if (list.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "用户名称已存在",
                    Data = -1
                };
            }
            else
            {
                //异步事务
                using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        request.Apps.App_Time = DateTime.Now;
                      await  Apps.AddAsync(request.Apps);
                        RoleApp roleApp = new RoleApp
                        {
                            RoleApp_Id = 0,
                            //Role_Id = Convert.ToInt32(request.Apps.Role_ArrId[0]),
                            Role_Id =3,
                            App_Id = request.Apps.App_Id
                        };
                       await RoleApps.AddAsync(roleApp);
                        scope.Complete();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }


                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "添加应用成功",
                    Data = 1

                };
            }

        }
    }
}
